/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lx_easyfinace.util;

import DB.DatabaseManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Color;
import model.Constants;
import model.Guest;
import model.Product;
import model.Sell;
import model.SellItem;
import model.TableInterface;
import model.Vendor;

/**
 *
 * @author lcnkb24
 * 是否创建一个可以实例化自身的接口?
 */
public class DataOperateUtil {

    private final boolean DEBUG = true;
    /**
     * 数据库管理
     */
    private DatabaseManager dbm = new DatabaseManager();

    /**
     * 新增用户数据
     * @param g 用户
     * @param records 记录
     * @return -1数据添加出错 / 1添加成功
     */
    public int addSellItemRecords(Object[] g, Object[] records, Sell sell) {
        //TODO 是不是该再做一些检查工作?例如user和records是否已经正确赋值了?  (暂时不做.)

        String gName = g[0].toString();
        String gPhone = g[1].toString();
        String gAddrs = g[2].toString();

        Date date = CalculateUtil.calculateFormatDate(records[0].toString());
        String pName = records[1].toString();
        String color = records[2].toString();
        String quantity = records[3].toString();
        float perPrice = Float.parseFloat(records[4].toString());
        float subtotal = Float.parseFloat(records[5].toString());
//        float payed = Float.parseFloat(records[6].toString());
//        float unpay = Float.parseFloat(records[7].toString());

        Guest guest = null;
        Product product = null;
//        Sell sell = null;
        SellItem[] sis = null;
        try {
            guest = createGuest(gName, gPhone, gAddrs);
            product = createProduct(pName, perPrice, Constants.STORAGE_UNKNOW, null);
//            sell = createSell(Constants.SELL_STATUS_UNKNOW, subtotal, date);
            sis = createSellItem((quantity), perPrice, product.getpId(), color);
        } catch (SQLException ex) {
            Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }


        logicProcess(guest, product, sell, sis);

        //设置一个手动提交的事务，以保证所有数据正确插入
        try {
            DatabaseManager.oracleConnect.setAutoCommit(false);
            getDbm().sell(guest, sell, product, sis);
            DatabaseManager.oracleConnect.commit();
            DatabaseManager.oracleConnect.setAutoCommit(true);
            //        Product product = createProduct(null, pprice, pstorage, null);
        } catch (SQLException ex) {
            Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex);
            try {
                DatabaseManager.oracleConnect.rollback();
                DatabaseManager.oracleConnect.setAutoCommit(true);
            } catch (SQLException ex1) {
                Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex1);
            }
        } finally {
            System.out.println("关闭相应链接");
        }
        return 1;
    }

    public Sell addSellRecords(Object[] g, Object[] records) {
        String gName = g[0].toString();
        String gPhone = g[1].toString();
        String gAddrs = g[2].toString();

        Sell sell = new Sell();
        sell.setsDate(CalculateUtil.calculateFormatDate(records[0].toString()));
        try {
            sell.setsId(dbm.getIDNums(sell));
        } catch (SQLException ex) {
            Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        sell.setsStutus(Constants.SELL_STATUS_PAYED);
        sell.setPname(records[1].toString());
        sell.setQuantity(records[2].toString());
        sell.setPrice(Float.parseFloat(records[5].toString()));
        sell.setsTotalPrice(Float.parseFloat(records[6].toString()));
        sell.setPayed(Float.parseFloat(records[7].toString()));

        Guest guest = null;
        try {
            guest = createGuest(gName, gPhone, gAddrs);
            sell.setsGuest(guest);
            dbm.insertData(sell);
        } catch (SQLException ex) {
            Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
        return sell;
    }

    /**
     * 获取已有信息，如品名，颜色等等
     * @param query
     * @param tableName
     * @return 
     */
    public List<String> getExistInfo(String query, String tableName) {
        List<String> list = null;
        try {
            list = getDbm().query(query, tableName);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        list.add(0, "");
        return list;
    }

    public List<Guest> getExistGuests() {
        List<Guest> list = null;
        try {
            list = getDbm().querGuest();
        } catch (SQLException ex) {
            Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        //第一个位置设为空
        Guest tempGuest = new Guest();
        tempGuest.setgName("");
        list.add(0, tempGuest);

        return list;
    }

    /**
     * 根据客户姓名，获取已有记录
     * @param name 名字
     * @return
     */
    public List<String> getData(String name) {
        List<String> list = null;
        try {
            list = getDbm().queryData(name);
        } catch (SQLException ex) {
            Logger.getLogger(DataOperateUtil.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("获取客户已有记录失败");
        }
        return list;
    }

    public Object getObj(TableInterface table, String queryKey, String queryCondition) {
        return getDbm().getObj(table, queryKey, queryCondition);
    }

    /**
     * 进行实际数据插入的逻辑处理
     * 
     * @param guest 客户
     * @param product 产品
     * @param sell 销售记录
     * @param sis 销售细节
     */
    private void logicProcess(Guest guest, Product product, Sell sell, SellItem[] sis) {

//        guest = (Guest) getDbm().getObj(guest, "gname", guest.getgName());
//        if (guest.isExist()) {
//            System.out.println("老客户了...");
//        } else {
//            System.out.println("新客户呢...");
//        }


        //指定这是那位客户的销售记录
//        sell.setsGuest(guest);

        //暂时未进行产品厂商的设置,暂设一个默认值,回头再完善.
        Vendor v = new Vendor();
        v.setvId(-1);

        product.setVendor(v);

        for (SellItem si : sis) {
            si.setSiProduct(product);
            si.setSiSell(sell);
            si.setSiSubTotal(si.getSiProductNum() * si.getSiperprice());
        }
    }

    /**
     * 实例化一位用户
     */
    private Guest createGuest(String gname, String gphone, String gaddress) throws SQLException {
        Guest g = new Guest();
        g.setgId(getDbm().getIDNums(g));
        g.setgName(gname);
        g.setgPhone(gphone);
        g.setgAddress(gaddress);

        g = (Guest) getDbm().getObj(g, "gname", g.getgName());
        if (g.isExist()) {
            System.out.println("老客户了...");
        } else {
            System.out.println("新客户呢...");
            dbm.insertData(g);
        }

        return g;

    }

    /**
     * 实例化产品
     * @param pName 品名
     * @param pprice 单价
     * @param pstorage 库存
     * @param pimg 产品图片
     * @return
     */
    public Product createProduct(String pName, double pprice, double pstorage, String pimg) throws SQLException {

        Product p = new Product();
        p = (Product) getDbm().getObj(p, "pname", pName);
        if (p.isExist()) {
            return p;
        } else {
            p.setpId(getDbm().getIDNums(p));
            p.setpName(pName);
            p.setpPrice(pprice);
            p.setpStorage(pstorage);
            p.setpImg(pimg);
            dbm.insertData(p);
            return p;
        }
    }

    public Color createColor(String colorNum, Product p) throws SQLException {
        int cid = -2;

        cid = getDbm().getProductColorID(colorNum, p.getpId());

        model.Color color = new model.Color();
        color = (model.Color) getDbm().getObj(color, "cid", String.valueOf(cid));
        if (!color.isExist()) {
            color.setCid(getDbm().getIDNums(color));
            color.setPid(p.getpId());
            color.setColornum(colorNum);
            dbm.insertData(color);
            return color;
        } else {
            return color;
        }
    }

    /**
     *
     * @param sstatus 销售状态(未知、已付、未付、退货)
     * @param stotalprice 合计价格
     * @param sdate 销售日期
     * @param ssellquantity 销售数量
     * @return
     */
    private Sell createSell(int sstatus, double stotalprice, Date sdate) throws SQLException {
        Sell s = new Sell();
        s.setsId(getDbm().getIDNums(s));
        s.setsStutus(sstatus);
        s.setsTotalPrice(stotalprice);
        s.setsDate(sdate);
//        s.setsSellQuantity(ssellquantity);
        return s;

    }

    /**
     * 详细记录每一匹布料的信息
     * @param quantity
     * @return
     */
    private SellItem[] createSellItem(String quantity, float perPrice, int pid, String colorNum) throws SQLException {

        float[] quantitys = CalculateUtil.calculateQuantitys(quantity);
        SellItem[] sis = new SellItem[quantitys.length];
        int siid = getDbm().getIDNums(new SellItem());

        int cid = getDbm().getProductColorID(colorNum, pid);
        //颜色信息
        Color color = new Color();
        color = (Color) getDbm().getObj(color, "cid", String.valueOf(cid));
        if (!color.isExist()) {
            color.setCid(getDbm().getIDNums(color));
            color.setPid(pid);
            color.setColornum(colorNum);
//            color.setColordesc("红色");
//            color.setExist(true);
        }

        for (int i = 0; i < sis.length; i++) {
            SellItem si = new SellItem();
            si.setSiId(siid++);
            si.setSiProductNum(quantitys[i]);
            si.setSiperprice(perPrice);
            if (color.getCid() > 0) {
                si.setSiColor(color);
            }
            sis[i] = si;
        }
        return sis;

    }

    /**
     * 单个测试
     * @param args
     */
    public static void main(String[] args) {
        List<Guest> list = new DataOperateUtil().getExistGuests();

        for (Guest guest : list) {
            System.out.println(guest);
        }

    }

    /**
     * @return the dbm
     */
    public DatabaseManager getDbm() {
        return dbm;
    }
}
